package cn.dapeng.base;

import cn.dapeng.util.SleepingUtil;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadState {

    public static void main(String[] args) throws Exception {
        // ------------------------------------------
        Thread t1 = new Thread(() -> {
            System.out.println("2. " + Thread.currentThread().getState());

            for (int i = 0; i < 3; i++) {
                SleepingUtil.sleep(1, TimeUnit.SECONDS);
            }
        });

        System.out.println("1. " + t1.getState());
        t1.start();
        t1.join();
        System.out.println("3. " + t1.getState());

        // ------------------------------------------
        Thread t2 = new Thread(() -> {
            LockSupport.park();
            System.out.println("t2 go on!");
            SleepingUtil.sleep(5, TimeUnit.SECONDS);
        });

        t2.start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        System.out.println("4: " + t2.getState());

        LockSupport.unpark(t2);
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        System.out.println("5: " + t2.getState());

        t2.join();
        System.out.println("6: " + t2.getState());

        // ------------------------------------------
        Object monitor = new Object();
        Thread t3 = new Thread(() -> {
            synchronized (monitor) {
                System.out.println("t3 go on!");
            }
        });

        new Thread(() -> {
            synchronized (monitor) {
                SleepingUtil.sleep(5, TimeUnit.SECONDS);
            }
        }).start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);

        t3.start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        System.out.println("7. " + t3.getState());

        // ------------------------------------------

        ReentrantLock lock = new ReentrantLock();

        Thread t4 = new Thread(() -> {
            lock.lock();
            System.out.println("t4 go on!");
            lock.unlock();
        });

        new Thread(() -> {
            lock.lock();
            SleepingUtil.sleep(5, TimeUnit.SECONDS);
            lock.unlock();
        }).start();

        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        t4.start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        System.out.println("8. " + t4.getState());
    }
}
